var wxCharts = require('../../utils/wxcharts.js');
const app = getApp();
var areaChart = null;
var startPos = null;
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({

  /**
   * 页面的初始数据
   */
  data: {
    auth: app.auth,
    weekRuns: [],
    monthRuns: [],
    listData: [],
    target: 0,
    reportType: 'week',
    tabs: [],
    activeIndex: 5,
    sliderOffset: 0,
    sliderLeft: 0,
    lastX:0,
    lastY:0
  },
  loadTabs:function(){
    var self = this;
    var threeSession = app.get3Session();
    wx.request({
      url: app.globalData.domain + 'report/tabs?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        var tab = new Array();
        for (var i =0;i<data.data.length;i++){
          tab.push(data.data[i] + '月');
        }
        self.setData({
          tabs: tab,
        });
        wx.getSystemInfo({
          success: function (res) {
            self.setData({
              sliderLeft: -(res.windowWidth / self.data.tabs.length - sliderWidth) / 4,
              sliderOffset: res.windowWidth / self.data.tabs.length * self.data.activeIndex
            });
          }
        });
        self.loadCountData(self.data.activeIndex);
      }
    });
  },
  touchHandler: function (e) {
    var startx = e.touches[0].x
    var starty = e.touches[0].y
    this.setData({
      lastX : startx,
      lastY : starty
    });
  },
  touchEnd:function(e){
    var text ='';
    var currentX = e.changedTouches[0].x
    var currentY = e.changedTouches[0].y
    var tx = currentX - this.data.lastX
    var ty = currentY - this.data.lastY
    if (currentX == this.data.lastX && currentY == this.data.lastY){
      areaChart.showToolTip(e, {
        // background: '#7cb5ec',
        format: function (item, category) {
          return category + ' ' + item.name + ':' + item.data
        }
      });
    }
    if (this.data.activeIndex != 5) {
      return;
    }
    //左右方向滑动
    if (Math.abs(tx) > Math.abs(ty)) {
      if (tx < -30){
        text = "向左滑动"
        this.switch2Change();  
      }else if (tx > 30){
        text = "向右滑动"
        this.switch2Change();  
      }
    }else if (Math.abs(tx) <= Math.abs(ty)) {
      if (tx < -30) {
        text = "向上滑动"
        this.switch2Change();
      } else if (tx > 30) {
        text = "向下滑动"
        this.switch2Change();
      }
    }
  },
  switch2Change: function (e) {
    var self = this;
    var reportType = self.data.reportType;
    var series = null;
    var categories = null;
    if (reportType == 'week'){
      series = [
        {
          name: '目标步数',
          data: self.data.monthRuns.target,
          format: function (val) {
            return val;
          }
        }, {
          name: '实际步数',
          data: self.data.monthRuns.data,
          format: function (val) {
            return val;
          }
        },
      ];
      categories = self.data.monthRuns.categories;
      self.setData({
        reportType: 'month'
      });
    } else if (reportType == 'month') {
      series = [
        {
          name: '目标步数',
          data: self.data.weekRuns.target,
          format: function (val) {
            return val;
          }
        }, {
          name: '实际步数',
          data: self.data.weekRuns.data,
          format: function (val) {
            return val;
          }
        },
      ];
      categories = self.data.weekRuns.categories;
      self.setData({
        reportType: 'week'
      });
    }
    areaChart.updateData({
      categories: categories,
      series: series
    });
    
  },
  setAuth: function (e) {
    app.countAuthReadyCallback = res => {
      this.setData({
        auth: true
      })
    }
  },
  tabClick: function (e) {
    var self = this;
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    self.loadCountData(self.data.activeIndex);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  loadCountData:function(index){
    var self = this;
    var threeSession = app.get3Session();
    wx.request({
      url: app.globalData.domain + 'report/userStepsInfo?threeSession=' + threeSession+"&index="+index,
      dataType: 'json',
      success: function (data) {
        if (data == null || data.data == null || data.data == 'fail' || data.data =='empty threeSession'){
          app.checkSession();
        }
        self.setData({
          weekRuns: data.data[0],
          monthRuns: data.data[1],
          target: data.data[0].target
        });
        if (self.data.activeIndex == 5){
          self.initCharts(self.data.weekRuns);
        }else{
          self.initCharts(self.data.monthRuns);
        }
      }
    });
    wx.request({
      url: app.globalData.domain + 'report/tableItems?threeSession=' + threeSession + "&index=" + index,
      dataType: 'json',
      success: function (data) {
        self.setData({
          listData: data.data,
        });
      }
    });
  },

  initCharts: function (options) {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
    }
    var id = 'areaCanvas'+this.data.activeIndex;

    areaChart = new wxCharts({
      canvasId: id,
      type: 'area',
      categories: options.categories,
      animation: false,
      background: '#007d53',
      series: [{
        name: '目标步数',
        data: options.target,
        format: function (val) {
          return val;
        }
      },{
        name: '实际步数',
        data: options.data,
        format: function (val) {
          return val;
        }
      },
      ],
      yAxis: {
        title: '',
        format: function (val) {
          return val;
        },
        min: 0,
        fontColor: '#8085e9',
        gridColor: '#FFFFFF',
        titleFontColor: '#f7a35c',
      },
      xAxis: {
        fontColor: '#7cb5ec',
        gridColor: '#FFFFFF',
        disableGrid: true,
      },
      dataLabel: false,
      extra: {
        legendTextColor: '#cb2431'
      },
      width: windowWidth,
      height: 250,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.get3Session();
    this.myShow();
  },
  myShow:function(){
    var self = this;

    self.setData({
      auth: app.globalData.auth
    });
    if (!this.data.auth) {
      return;
    }
    this.loadTabs();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onShareAppMessage: function (ops) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: 'MEDATA',
      path: 'pages/step/step',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
})